<template>
    <div class="teacher-review-container">
        <div class="filter-container">
            <el-form :inline="true" :model="listQuery" class="demo-form-inline">
                <el-form-item label="成果类型">
                    <el-select v-model="listQuery.achievementType" placeholder="请选择成果类型" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="论文" :value="1" />
                        <el-option label="专利" :value="2" />
                        <el-option label="竞赛证书" :value="3" />
                        <el-option label="项目计划" :value="4" />
                        <el-option label="其他" :value="5" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-select v-model="listQuery.status" placeholder="请选择审核状态" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="待初审" :value="0" />
                        <el-option label="初审通过" :value="1" />
                        <el-option label="初审拒绝" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="listQuery.studentName" placeholder="请输入学生姓名" style="width: 150px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item label="成果标题">
                    <el-input v-model="listQuery.title" placeholder="请输入成果标题" style="width: 200px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleFilter">
                        搜索
                    </el-button>
                    <el-button icon="el-icon-refresh" @click="handleReset">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
            style="width: 100%">
            <el-table-column align="center" label="ID" width="80">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="学生信息" width="150" align="center">
                <template slot-scope="scope">
                    <div>
                        <div>{{ scope.row.studentName }}</div>
                        <div class="text-muted" style="font-size: 12px;">{{ scope.row.account }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="成果标题" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span>{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="成果类型" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.achievementType)">
                        {{ getTypeLabel(scope.row.achievementType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="级别" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.level" size="small" :type="getLevelTagType(scope.row.level)">
                        {{ getLevelLabel(scope.row.level) }}
                    </el-tag>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="学院专业" width="180" align="center">
                <template slot-scope="scope">
                    <div>
                        <div>{{ scope.row.department }}</div>
                        <div class="text-muted" style="font-size: 12px;">{{ scope.row.major }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="绑定课程" width="150" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.course">{{ scope.row.course }}</span>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="审核状态" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="提交时间" width="160" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="附件" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-dropdown v-if="scope.row.attachments && scope.row.attachments.length > 0" trigger="click">
                        <el-button type="text" size="small" class="attachment-btn">
                            附件下载 <i class="el-icon-arrow-down el-icon--right" />
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                class="attachment-item" @click.native="handleDownloadAttachment(file)">
                                <i :class="getFileIcon(file.fileType)" class="file-icon" />
                                <span class="file-name">{{ file.name }}</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleView(scope.row)">
                        查看详情
                    </el-button>
                    <el-button v-if="scope.row.status === 0" type="success" size="mini"
                        @click="handleApprove(scope.row)">
                        通过
                    </el-button>
                    <el-button v-if="scope.row.status === 0" type="danger" size="mini" @click="handleReject(scope.row)">
                        拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
            @pagination="getList" />

        <!-- 审核对话框 -->
        <el-dialog :title="reviewDialogTitle" :visible.sync="reviewDialogVisible" width="500px"
            @close="resetReviewForm">
            <el-form ref="reviewForm" :model="reviewForm" :rules="reviewRules" label-width="100px">
                <el-form-item label="审核结果">
                    <el-tag :type="reviewForm.status === 1 ? 'success' : 'danger'">
                        {{ reviewForm.status === 1 ? '通过' : '拒绝' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="审核意见" prop="comment">
                    <el-input v-model="reviewForm.comment" type="textarea" :rows="4"
                        :placeholder="reviewForm.status === 1 ? '请输入通过理由（可选）' : '请输入拒绝理由'" maxlength="500"
                        show-word-limit />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reviewDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmReview" :loading="reviewLoading">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getTeacherReviewList, teacherReview } from '@/api/achievement'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
    name: 'TeacherReview',
    components: { Pagination },
    filters: {
        parseTime(time, pattern) {
            return parseTime(time, pattern)
        }
    },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                studentName: '',
                title: ''
            },
            reviewDialogVisible: false,
            reviewDialogTitle: '',
            reviewLoading: false,
            currentRow: null,
            reviewForm: {
                id: '',
                status: 1, // 1-通过, 2-拒绝
                comment: ''
            },
            reviewRules: {
                comment: [
                    { validator: this.validateReviewComment, trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getList();
    },
    methods: {
        async getList() {
            this.listLoading = true;
            try {
                const res = await getTeacherReviewList(this.listQuery)
                this.list = res.data.records || [];
                this.total = res.data.total || 0;
                this.list.forEach(item => {
                    // 解析附件URL
                    if (item.fileUrl) {
                        try {
                            item.attachments = JSON.parse(item.fileUrl)
                        } catch (e) {
                            item.attachments = []
                        }
                    } else {
                        item.attachments = []
                    }
                })
            } catch (error) {
                console.error('获取待审核成果列表失败:', error)
            } finally {
                this.listLoading = false
            }
            // 模拟数据
            /*  setTimeout(() => {
                 const mockData = {
                     records: [
                         {
                             id: 1,
                             title: '基于机器学习的股票预测模型研究',
                             achievementType: 1,
                             tags: '国家级',
                             courseName: '机器学习',
                             semester: '2024-2025-1',
                             status: 0,
                             studentName: '张三',
                             studentNumber: '2021001001',
                             department: '计算机科学与技术学院',
                             createTime: '2024-10-19 10:30:00',
                             attachmentUrl: JSON.stringify([
                                 {
                                     name: '研究论文.pdf',
                                     url: 'https://example.com/ml_paper.pdf',
                                     fileType: 'pdf',
                                     size: 3145728
                                 },
                                 {
                                     name: '实验代码.zip',
                                     url: 'https://example.com/code.zip',
                                     fileType: 'zip',
                                     size: 1048576
                                 }
                             ])
                         },
                         {
                             id: 2,
                             title: '智能农业监测系统专利申请',
                             achievementType: 2,
                             tags: '省级',
                             courseName: '物联网工程',
                             semester: '2024-2025-1',
                             status: 0,
                             studentName: '李四',
                             studentNumber: '2021001002',
                             department: '物联网工程学院',
                             createTime: '2024-10-18 14:20:00',
                             attachmentUrl: JSON.stringify([
                                 {
                                     name: '专利申请材料.pdf',
                                     url: 'https://example.com/patent_application.pdf',
                                     fileType: 'pdf',
                                     size: 2097152
                                 }
                             ])
                         },
                         {
                             id: 3,
                             title: 'ACM程序设计竞赛银奖',
                             achievementType: 3,
                             tags: '国家级',
                             courseName: '算法设计与分析',
                             semester: '2024-2025-1',
                             status: 1,
                             studentName: '王五',
                             studentNumber: '2021001003',
                             department: '计算机科学与技术学院',
                             createTime: '2024-10-15 09:45:00',
                             teacherReviewComment: '该同学在ACM竞赛中表现优异，算法能力突出，值得表彰。',
                             teacherReviewTime: '2024-10-17 16:30:00',
                             attachmentUrl: JSON.stringify([
                                 {
                                     name: '获奖证书.jpg',
                                     url: 'https://example.com/acm_certificate.jpg',
                                     fileType: 'jpg',
                                     size: 1572864
                                 }
                             ])
                         },
                         {
                             id: 4,
                             title: '校园共享单车管理系统设计',
                             achievementType: 4,
                             tags: '校级',
                             courseName: '软件工程',
                             semester: '2024-2025-1',
                             status: 2,
                             studentName: '赵六',
                             studentNumber: '2021001004',
                             department: '软件工程学院',
                             createTime: '2024-10-12 11:15:00',
                             teacherReviewComment: '项目设计思路不够清晰，技术方案需要进一步完善，建议重新修改后再次提交。',
                             teacherReviewTime: '2024-10-16 14:20:00',
                             attachmentUrl: JSON.stringify([
                                 {
                                     name: '项目设计文档.docx',
                                     url: 'https://example.com/project_design.docx',
                                     fileType: 'docx',
                                     size: 2621440
                                 }
                             ])
                         }
                     ],
                     total: 4
                 }
 
                 // 解析附件URL
                 this.list = mockData.records.map(item => {
                     if (item.attachmentUrl) {
                         try {
                             item.attachments = JSON.parse(item.attachmentUrl)
                         } catch (e) {
                             item.attachments = []
                         }
                     } else {
                         item.attachments = []
                     }
                     return item
                 })
                 this.total = mockData.total
                 this.listLoading = false
             }, 1000)
          */
        },
        handleFilter() {
            this.listQuery.pageNo = 1
            this.getList()
        },
        handleReset() {
            this.listQuery = {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                studentName: '',
                keyword: ''
            }
            this.getList()
        },
        handleView(row) {
            // 跳转到成果详情页面
            this.$router.push(`/achievement/detail/${row.id}`)
        },
        handleApprove(row) {
            this.currentRow = row
            this.reviewForm.id = row.id
            this.reviewForm.status = 1
            this.reviewForm.comment = ''
            this.reviewDialogTitle = '初审通过'
            this.reviewDialogVisible = true
        },
        handleReject(row) {
            this.currentRow = row
            this.reviewForm.id = row.id
            this.reviewForm.status = 2
            this.reviewForm.comment = ''
            this.reviewDialogTitle = '初审拒绝'
            this.reviewDialogVisible = true
        },
        confirmReview() {
            this.$refs.reviewForm.validate((valid) => {
                if (valid) {
                    this.reviewLoading = true
                    teacherReview(this.reviewForm).then(() => {
                        this.$message.success('审核完成!')
                        this.reviewDialogVisible = false
                        this.getList()
                    }).catch(() => {
                        this.$message.error('审核失败')
                    }).finally(() => {
                        this.reviewLoading = false
                    })
                }
            })
        },
        resetReviewForm() {
            this.reviewForm = {
                id: '',
                status: 1,
                comment: ''
            }
            this.currentRow = null
            if (this.$refs.reviewForm) {
                this.$refs.reviewForm.resetFields()
            }
        },
        validateReviewComment(rule, value, callback) {
            if (this.reviewForm.status === 2 && (!value || value.trim() === '')) {
                callback(new Error('拒绝时必须填写拒绝理由'))
            } else {
                callback()
            }
        },
        handleDownloadAttachment(file) {
            window.open(file.url, '_blank')
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '论文',
                2: '专利',
                3: '竞赛证书',
                4: '项目计划',
                5: '其他'
            }
            return typeMap[type] || '未知'
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                4: 'info',
                5: 'danger'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                0: '待初审',
                1: '初审通过',
                2: '初审拒绝'
            }
            return statusMap[status] || '未知'
        },
        getStatusTagType(status) {
            const statusMap = {
                0: 'info',
                1: 'success',
                2: 'danger'
            }
            return statusMap[status] || ''
        },
        getLevelLabel(level) {
            const levelMap = {
                1: '国家级',
                2: '省级',
                3: '市级',
                4: '校级'
            }
            return levelMap[level] || '未知'
        },
        getLevelTagType(level) {
            const levelMap = {
                1: 'danger',   // 国家级 - 红色
                2: 'warning',  // 省级 - 橙色
                3: 'primary',  // 市级 - 蓝色
                4: 'success'   // 校级 - 绿色
            }
            return levelMap[level] || 'info'
        },
        getFileIcon(fileType) {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'jpg': 'el-icon-picture',
                'jpeg': 'el-icon-picture',
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture'
            }
            return iconMap[fileType] || 'el-icon-document'
        }
    }
}
</script>

<style lang="scss" scoped>
.teacher-review-container {
    padding: 20px;
}

.filter-container {
    padding-bottom: 20px;
}


.text-muted {
    color: #999;
}

.attachment-btn {
    padding: 0;
    font-size: 12px;
}

.attachment-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    cursor: pointer;

    &:hover {
        background-color: #f5f7fa;
    }
}

.file-icon {
    margin-right: 8px;
    color: #409EFF;
}

.file-name {
    font-size: 12px;
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>